<?php
/**
 * @author 刘国君
 * @version 1.0
 * 查考 https://github.com/ideawu/phpvoip/blob/master/net/SipMessage.php
 * 解析header头部
 */

namespace app\Protocols;

use app\Handel\SipContact;
use app\Handel\SipMessage;
use Workerman\Connection\UdpConnection;

class Sip
{
    public static function input($recv_buffer, UdpConnection $connection)
    {
        //结尾
        if (!strpos($recv_buffer, "\r\n\r\n")) {
            return 0;
        }
        //获得header
        list($header,) = explode("\r\n\r\n", $recv_buffer, 2);
        try {
            $l = self::parse($header);
            return $l;
        } catch (\Exception $e) {
            $connection->close();
            return 0;
        }
    }

    protected static function parse($header)
    {
        $match = [];
        if (preg_match("/Content-Length:( +)?(\d+)/i", $header, $match)) {
            $content_length = isset($match[2]) ? $match[2] : 0;
        } else {
            $content_length = 0;
        }
        return $content_length + strlen($header) + 4;
    }

    public static function decode($recv_buffer, UdpConnection $connection)
    {
        var_dump($recv_buffer);
       $sip_message=new SipMessage();
       $sip_message->decode($recv_buffer);
       return $sip_message;
    }
    public static function encode($msg, UdpConnection $connection)
    {
        return $msg;
    }
}

